from sqlalchemy import Column, String, Integer, ForeignKey, DateTime, Text, JSON
from sqlalchemy.orm import relationship
from enum import Enum as PyEnum

from app.models.base import Base


class ReportType(PyEnum):
    PROJECT_STATUS = "project_status"  # 项目状态报表
    RESOURCE_UTILIZATION = "resource_utilization"  # 资源利用率报表
    RISK_ANALYSIS = "risk_analysis"  # 风险分析报表
    PROGRESS_TRACKING = "progress_tracking"  # 进度跟踪报表
    FINANCIAL = "financial"  # 财务报表
    CUSTOM = "custom"  # 自定义报表


class ReportFrequency(PyEnum):
    DAILY = "daily"  # 每日
    WEEKLY = "weekly"  # 每周
    BIWEEKLY = "biweekly"  # 双周
    MONTHLY = "monthly"  # 每月
    QUARTERLY = "quarterly"  # 每季度
    YEARLY = "yearly"  # 每年
    CUSTOM = "custom"  # 自定义
    ONCE = "once"  # 一次性


class Report(Base):
    """报表模型"""
    name = Column(String(100), nullable=False, index=True)
    description = Column(Text, nullable=True)
    report_type = Column(String(30), nullable=False)
    frequency = Column(String(20), nullable=False, default=ReportFrequency.ONCE.value)
    parameters = Column(JSON, nullable=True)  # 报表参数
    template = Column(Text, nullable=True)  # 报表模板
    last_generated = Column(DateTime, nullable=True)  # 上次生成时间
    next_scheduled = Column(DateTime, nullable=True)  # 下次计划生成时间
    
    # 外键
    creator_id = Column(Integer, ForeignKey("user.id"), nullable=False)
    project_id = Column(Integer, ForeignKey("project.id"), nullable=True)  # 可能是项目级别或项目集级别
    
    # 关系
    creator = relationship("User")
    project = relationship("Project", back_populates="reports")
    report_instances = relationship("ReportInstance", back_populates="report_template")


class ReportInstance(Base):
    """报表实例模型（已生成的报表）"""
    file_path = Column(String(255), nullable=False)  # 报表文件路径
    generation_date = Column(DateTime, nullable=False)  # 生成日期
    parameters_used = Column(JSON, nullable=True)  # 使用的参数
    
    # 外键
    report_template_id = Column(Integer, ForeignKey("report.id"), nullable=False)
    generator_id = Column(Integer, ForeignKey("user.id"), nullable=False)  # 生成者（可能是系统或用户）
    
    # 关系
    report_template = relationship("Report", back_populates="report_instances")
    generator = relationship("User")